package com.example.seh.chat;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.example.seh.R;
import com.example.seh.UserDTO;
import com.example.seh.constant.Constant;
import com.example.seh.home.secondhand.GoodsDTO;
import com.example.seh.util.ChatUtil;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ChatFragment extends Fragment {
    private ListView chatlist;
    private List<ChatUserDTO> marketers = new ArrayList<>();
    private TextView market, chatMsg;
    private ChatAdapter adapter;
    private boolean isFirst = true;
    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, null);
        System.out.println("chatfragment执行");
        getViews(view);
        initDatas();


        return view;
    }

    private void initDatas() {
        System.out.println("islogin:" + Constant.isLogin);
        if (Constant.isLogin == true) {
            Log.e("chatlogin","login");
            chatMsg.setVisibility(View.VISIBLE);
            market.setVisibility(View.INVISIBLE);
            chatlist.setVisibility(View.VISIBLE);
            getData();
            adapter = new ChatAdapter(
                    getContext(),
                    marketers,
                    R.layout.fragment_chat_item
            );
            chatlist.setAdapter(adapter);

        } else {
            Log.e("chatlogin","exit");
            chatMsg.setVisibility(View.INVISIBLE);
            market.setVisibility(View.VISIBLE);
            chatlist.setVisibility(View.INVISIBLE);
        }
        Bundle bundle = this.getArguments();
        System.out.println("bundle : " + bundle);
        if (bundle != null && bundle.getBoolean("isEdit")) {
            System.out.println("change");
            chatMsg.setVisibility(View.INVISIBLE);
            market.setVisibility(View.VISIBLE);
            chatlist.setVisibility(View.INVISIBLE);
        }


        setListeners();
    }

    private void setListeners() {
        chatlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getContext(), ChatActivity.class);
                UserDTO userDTO = marketers.get(position).getUserDTO();
                Log.e("chatlist","点击的user:" + userDTO.toString());
                intent.putExtra("user", userDTO);
                if (userDTO.getPic() != null) {
                    Log.e("avatar",userDTO.getUsername() + "有头像");
                    ChatUtil.youAvatar = userDTO.getPic();
                }
                if (UserMsg.userDTO.getPic() != null) {
                    Log.e("avatar",UserMsg.userDTO.getUsername() + "有头像");
                    ChatUtil.myAvatar = UserMsg.userDTO.getPic();
                }
                startActivity(intent);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Constant.isLogin) {
            if (!isFirst) {
                Log.e("chatlogin", "登录后加载");
                initDatas();
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
            isFirst = false;
        } else {
            if (!isFirst) {
                initDatas();
            }
        }
    }

    private void getViews(View view) {
        chatlist = view.findViewById(R.id.chat_listview);
        market = view.findViewById(R.id.market);
        chatMsg = view.findViewById(R.id.chat_msg);
    }


    private void getData() {
//        List<Marketers> marketers = new ArrayList<>();
//        Marketers m1 = new Marketers();
//        m1.setAvatar(R.drawable.banner1);
//        m1.setName("java");
//        m1.setTime("2023-05-05");
//
//        Marketers m2 = new Marketers();
//        m2.setAvatar(R.drawable.banner2);
//        m2.setName("android");
//        m2.setTime("2023-05-05");
//
//        Marketers m3 = new Marketers();
//        m3.setAvatar(R.drawable.banner3);
//        m3.setName("spring");
//        m3.setTime("2023-05-05");
//
//        marketers.add(m1);
//        marketers.add(m2);
//        marketers.add(m3);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.FINDMSGLIST + "userId=" + UserMsg.userDTO.getUserId())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("chatlist","列表查询失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("chatlist",result);

//                Gson gson = new Gson();
//                Type type = new TypeToken<List<UserDTO>>(){}.getType();
//                List<UserDTO> list = gson.fromJson(result,type);
//                Log.e("chatlist",list.toString());
//                marketers.clear();
//                marketers.addAll(list);
//                Message message = new Message();
//                message.what = 1;
//                handler.sendMessage(message);
                Gson gson = new Gson();
                Type type = new TypeToken<List<ChatUserDTO>>(){}.getType();
                List<ChatUserDTO> list = gson.fromJson(result, type);
                Log.e("chatlist", list.toString());
                marketers.clear();
                marketers.addAll(list);
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

}